package com.yupi.yuaiagent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class HttpAiInvoke {

    private static final Log log = LogFactory.get(HttpAiInvoke.class);
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    public static void main(String[] args) {
        try {
            String response = callWithMessage();
            System.out.println(response);
        } catch (Exception e) {
            System.err.println("错误信息：" + e.getMessage());
        }
    }

    public static String callWithMessage() {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-plus");

        // 构建消息内容
        Map<String, String> systemMsg = new HashMap<>();
        systemMsg.put("role", "system");
        systemMsg.put("content", "You are a helpful assistant.");

        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", "你是谁？");

        Map<String, Object> input = new HashMap<>();
        input.put("messages", Arrays.asList(systemMsg, userMsg));
        requestBody.put("input", input);

        // 构建参数
        Map<String, String> parameters = new HashMap<>();
        parameters.put("result_format", "message");
        requestBody.put("parameters", parameters);

        // 发送HTTP请求
        try {
            log.info("开始发送AI请求，请求地址: {}", API_URL);
            log.debug("请求体内容: {}", requestBody);

            // 发送HTTP请求
            HttpResponse response = HttpRequest.post(API_URL)
                    .header("Authorization", "Bearer " + TestApiKey.API_KEY)
                    .header("Content-Type", "application/json")
                    .body(cn.hutool.json.JSONUtil.toJsonStr(requestBody))
                    .execute();

            // 记录响应状态
            log.info("收到响应，状态码: {}", response.getStatus());

            // 检查响应状态码
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                String responseBody = response.body();
                log.debug("响应体内容: {}", responseBody);
                return responseBody;
            } else {
                // 处理错误响应
                String errorBody = response.body();
                log.error("请求失败，状态码: {}，错误信息: {}", response.getStatus(), errorBody);
                throw new RuntimeException("API请求失败，状态码: " + response.getStatus() + "，响应: " + errorBody);
            }
        } catch (Exception e) {
            log.error("发送HTTP请求时发生异常", e);
            throw new RuntimeException("请求处理异常: " + e.getMessage(), e);
        }
    }
}
